﻿#include "chatwidget.h"
#include "ui_chatwidget.h"
#include <QFileDialog>
#include <QLabel>
#include <QMessageBox>
#include <QStandardPaths>
#include <private/qtextimagehandler_p.h>
#include "characterset.h"
#include "clientcallback.h"
#include "emotionwidget.h"
#include "imagetextexporter.h"
#include "OEasyScreenshot"

ChatWidget::ChatWidget(QWidget *parent) :
    QSplitter(parent),
    ui(new Ui::ChatWidget), emotionWidget(Q_NULLPTR)
{
    ui->setupUi(this);
    ui->textInput->installEventFilter(this);
    ui->textInput->document()->documentLayout()->registerHandler(QTextFormat::ImageObject, new QTextImageHandler(this));
    auto f = ui->textInput->font();
    f.setPixelSize(16);
    ui->textInput->setFont(f);

    f = ui->textShow->font();
    f.setPixelSize(16);
    ui->textShow->setFont(f);

    connect(ui->push_send, SIGNAL(clicked(bool)), this, SIGNAL(sendClicked()));
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

bool ChatWidget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->textInput&& event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->matches(QKeySequence::InsertParagraphSeparator)) {
            //TODO:判断配置
            emit sendClicked();
            return true;
        } else
            return false;
    }
    return false;
}

QString ChatWidget::getContent() const
{
    return ImageTextExporter(ui->textInput->document()).toHtml();
}

ChatListViewer *ChatWidget::getTextShow()
{
    return ui->textShow;
}

QPlainTextEdit *ChatWidget::getTextInput()
{
    return ui->textInput;
}

void ChatWidget::emotionClicked(QListWidgetItem *item)
{
    if(emotionWidget)
        emotionWidget->hide();
    QString path = item->data(Qt::ToolTipRole).toString(); //name
    if(!ui->textInput->document()->resource(QTextDocument::ImageResource, path).isValid())
    {
        QPixmap pix = item->data(Qt::DecorationRole).value<QPixmap>();
        ui->textInput->document()->addResource(QTextDocument::ImageResource, QUrl(path), pix);
    }
    QTextImageFormat format;
    format.setName(path);
    ui->textInput->textCursor().insertImage(format);
}

void ChatWidget::screenCaptured(QPixmap pixmap)
{
    handleSendImage(pixmap);
}

void ChatWidget::on_tool_emotion_clicked()
{
    if(!emotionWidget)
    {
        emotionWidget = new EmotionWidget(ui->widgetInput);
        connect(emotionWidget, &EmotionWidget::itemClicked, this, &ChatWidget::emotionClicked);
    }
    if(emotionWidget->isHidden())
    {
        emotionWidget->show();
        emotionWidget->setFocus();
    }
    else
        emotionWidget->hide();
}

void ChatWidget::on_tool_picture_clicked()
{
    QStringList locations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
    QString file = QFileDialog::getOpenFileName(this, QObject::trECSUTF8("选择图片"),
                                                locations.isEmpty()?QLatin1String("./"):locations.first(),
                                                QLatin1String("Images (*.bmp *.jpg *.jpeg *.png *.gif *.tif *.tiff)"));
    if(file.isEmpty())
        return;
    QPixmap pixmap(file);
    if(pixmap.width() > 1920 || pixmap.height() > 1080)
        pixmap = pixmap.scaled(1920, 1080, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    handleSendImage(pixmap);
}

void ChatWidget::on_tool_capture_clicked()
{
    connect(OEScreenshot::Instance(), SIGNAL(screenshotSaved(QPixmap)), this, SLOT(screenCaptured(QPixmap)), Qt::UniqueConnection);
}

void ChatWidget::handleSendImage(const QPixmap &pixmap)
{
    QMessageBox msgbox(QMessageBox::NoIcon,QObject::trECSUTF8("确认发送"),QString(),QMessageBox::Ok | QMessageBox::Cancel, this);
    QLabel*label = msgbox.findChild<QLabel*>("qt_msgbox_label");//qt_msgbox_informativelabel
    if(label)
    {
        if(pixmap.isNull())
            msgbox.setStandardButtons(QMessageBox::Cancel);
        else
        {
            label->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
            QSize maxSize(400, 300);
            label->setMaximumSize(maxSize);
            if(pixmap.width() > maxSize.width() || pixmap.height() > maxSize.height())
                label->setScaledContents(true);
            label->setAlignment(Qt::AlignCenter);
            label->setPixmap(pixmap);
        }
        if(msgbox.exec() == QMessageBox::Ok)
            emit sendImage(pixmap);
    }
}
